/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 2010. 8. 20, 오후 7:35:28
 */

package window;

import com.util.HttpUtil;
import com.util.R;
import crawler.PassionScout;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author SDS
 */
public class MainWindow extends javax.swing.JFrame {

    private PassionScout pluginPs = new PassionScout();
    private int pageIdx = 0;
    private boolean pageEnd = false;

    private final int pageCount = 5;

    private String retrieveDiv = pluginPs.URL_ALL;
    private int lastRetrieveDiv = 0;

    /** Creates new form MainWindow */
    public MainWindow() {

        initComponents();

        // 테이블 데이터셋 지정
        MainTableDs = (DefaultTableModel) MainTable.getModel();

        // 테이블 컬럼모델 갱신
        TableColumnModel tcm = MainTable.getColumnModel();
        for( int i = 0, iCnt = MainTable.getColumnCount(); i < iCnt; i++ ) {
            tcm.getColumn(i).setCellRenderer( new MyTableRenderer() );
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BtnRetrieve = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        MainTable = new javax.swing.JTable();
        BtnNext = new javax.swing.JButton();
        CbDiv = new javax.swing.JComboBox();
        BtnAll = new javax.swing.JButton();
        labelStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("일딴 패션스카우트만.... 사랑하는 순지용 (슈붕이가 ^-^)");

        BtnRetrieve.setText("조회");
        BtnRetrieve.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnRetrieveActionPerformed(evt);
            }
        });

        MainTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "등록일", "회사명", "브랜드", "모집내용", "자격요건", "학력", "마감일", "링크"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MainTable.setColumnSelectionAllowed(true);
        MainTable.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        MainTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MainTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(MainTable);
        MainTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        MainTable.getColumnModel().getColumn(0).setResizable(false);
        MainTable.getColumnModel().getColumn(0).setPreferredWidth(10);
        MainTable.getColumnModel().getColumn(1).setResizable(false);
        MainTable.getColumnModel().getColumn(1).setPreferredWidth(50);
        MainTable.getColumnModel().getColumn(2).setResizable(false);
        MainTable.getColumnModel().getColumn(2).setPreferredWidth(50);
        MainTable.getColumnModel().getColumn(3).setPreferredWidth(200);
        MainTable.getColumnModel().getColumn(4).setResizable(false);
        MainTable.getColumnModel().getColumn(4).setPreferredWidth(30);
        MainTable.getColumnModel().getColumn(5).setResizable(false);
        MainTable.getColumnModel().getColumn(5).setPreferredWidth(20);
        MainTable.getColumnModel().getColumn(6).setResizable(false);
        MainTable.getColumnModel().getColumn(6).setPreferredWidth(20);
        MainTable.getColumnModel().getColumn(7).setResizable(false);
        MainTable.getColumnModel().getColumn(7).setPreferredWidth(0);

        BtnNext.setText("다음페이지");
        BtnNext.setEnabled(false);
        BtnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnNextActionPerformed(evt);
            }
        });

        CbDiv.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "전체", "디자이너", "마케팅/홍보", "의류" }));
        CbDiv.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                CbDivItemStateChanged(evt);
            }
        });

        BtnAll.setText("전체조회");
        BtnAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnAllActionPerformed(evt);
            }
        });

        labelStatus.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelStatus.setText("0 페이지 조회완료");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 806, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(CbDiv, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 409, Short.MAX_VALUE)
                        .addComponent(BtnRetrieve)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BtnNext)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BtnAll))
                    .addComponent(labelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CbDiv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BtnAll)
                    .addComponent(BtnNext)
                    .addComponent(BtnRetrieve))
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelStatus)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * 초기 조회시
     * @param evt
     */
    private void BtnRetrieveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnRetrieveActionPerformed

        clearData();
        retrieveData();

    }//GEN-LAST:event_BtnRetrieveActionPerformed

    private void MainTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MainTableMouseClicked

        int row = MainTable.getSelectedRow();
        int col = MainTable.getSelectedColumn();

        if( col != 7 ) return;

        String url = (String) MainTableDs.getValueAt( row, 7 );
        url = url.replace( R.readAlready, "" );
        
        if( HttpUtil.openBrowser(url) ) {

            for( int jnx = 0, jnxCnt = MainTable.getColumnCount(); jnx < jnxCnt; jnx++ ) {
                String colVal = (String) MainTableDs.getValueAt( row, jnx );
                colVal = colVal.replace( R.readAlready, "" ) + R.readAlready;
                MainTableDs.setValueAt( colVal, row, jnx );
            }

        }

    }//GEN-LAST:event_MainTableMouseClicked

    /**
     * 연속 조회시
     * @param evt
     */
    private void BtnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnNextActionPerformed
        retrieveData();
    }//GEN-LAST:event_BtnNextActionPerformed

    /**
     * 콤보박스 변경시
     * @param evt
     */
    private void CbDivItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_CbDivItemStateChanged

        if( CbDiv.getSelectedIndex() != lastRetrieveDiv ) {
            BtnNext.setEnabled( false );
        } else {
            BtnNext.setEnabled( true );
        }

    }//GEN-LAST:event_CbDivItemStateChanged

    /**
     * 전체 조회시
     * @param evt
     */
    private void BtnAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAllActionPerformed
        clearData();
        while( ! pageEnd ) {
            retrieveData();
        }

    }//GEN-LAST:event_BtnAllActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnAll;
    private javax.swing.JButton BtnNext;
    private javax.swing.JButton BtnRetrieve;
    private javax.swing.JComboBox CbDiv;
    public javax.swing.JTable MainTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelStatus;
    // End of variables declaration//GEN-END:variables

    // 메인 테이블의 데이터셋
    private DefaultTableModel MainTableDs;

    /**
     * 데이터 조회하기
     */
    private void retrieveData() {

        lastRetrieveDiv = CbDiv.getSelectedIndex();

        switch( lastRetrieveDiv ) {
            case 0:    retrieveDiv = pluginPs.URL_ALL;          break;
            case 1:    retrieveDiv = pluginPs.URL_DESIGN;       break;
            case 2:    retrieveDiv = pluginPs.URL_MARKETING;    break;
            case 3:    retrieveDiv = pluginPs.URL_WEAR;         break;
        }

        if( pageEnd ) return;

        for( int inx = 0; inx < pageCount; inx++ ) {

            Vector<String[]> data = pluginPs.getData( retrieveDiv, pageIdx + 1 );

            if( data.isEmpty() ) {
                pageEnd = true;
                BtnNext.setEnabled( false );
                return;
            }

            for( int jnx = 0; jnx < data.size(); jnx++ ) {
                MainTableDs.addRow( data.get(jnx) );
            }

            pageIdx++;

            labelStatus.setText( pageIdx + "페이지 조회완료" );

        }

        BtnNext.setEnabled( true );
        MainTableDs.fireTableDataChanged();

    }

    /**
     * 테이블 지우기
     */
    private void clearData() {

        pageIdx = 0;
        pageEnd = false;

        while (MainTableDs.getRowCount()>0){
            MainTableDs.removeRow( 0 );
        }
        MainTableDs.fireTableDataChanged();
    }

}
